package com.soledroid;


import java.io.*;
import java.net.*;
import java.util.*;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.github.droidfu.widgets.WebImageView;
import com.soledroid.MapViewActivity.MyLocationListener;
import com.soledroid.Model.Canteen;

import android.*;
import android.util.FloatMath;
import android.view.*;
import android.app.*;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.location.LocationProvider;
import android.os.*;
import android.widget.*;
import android.widget.AdapterView.OnItemClickListener;

public class BrowseActivity extends Activity{
	private LayoutInflater mInflater;
	private LocationManager mLocationManager;
	private LocationListener mLocationListener;
	private String mProvider = LocationManager.GPS_PROVIDER;
	Location l;
	boolean drawn = false;
	public enum canteenCode {NONE, FASS, FOE, FOS, FORUM, BIZ, STAFF, SOC, SRC, UCC, UHALL, MED, YIH, CREATE, ERC };
	public String[] canteenName = {
		"None",
		"Faculty of Arts and Social Sciences",
		"Faculty of Engineering",
		"Faculty of Science",
		"Forum",
		"Mochtar Riady Building, NUS Business School",
		"NUS Staff Club",
		"School of Computing/ NUS Business School",
		"Sports and Recreation Center",
		"University Cultural Centre",
		"University Hall",
		"Yong Loo Yin School of Medicine",
		"Yusof Ishak House",
		"CREATE UTown",
		"Education Resource Centre (ERC) UTown"
	};
	protected boolean isDataLoaded;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.browse);
		
		Bundle b = this.getIntent().getExtras();
		if(b != null) {
			// get entity data from the intent passed by Digit
			String entity = b.getString("entity");
			String content = b.getString("content");
			int latitude = b.getInt("latitude",0);
			int longitude = b.getInt("longitude",0);

			// get the user current location
			int userLatitude = b.getInt("userLatitude",0);
			int userLongitude = b.getInt("userLongitude",0);

			if(canteenCode.valueOf(entity.split(" ")[1]) != canteenCode.NONE) {
				Intent i = new Intent(getApplicationContext(), CanteenActivity.class); 

				i.putExtra("name",  canteenName[canteenCode.valueOf(entity.split(" ")[1]).ordinal()]);
				i.putExtra("id", canteenCode.valueOf(entity.split(" ")[1]).ordinal());

				BrowseActivity.this.startActivity(i);
			}
		} else {
			drawn = true;

			mInflater = (LayoutInflater) getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
			isDataLoaded = false;
			mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
			mLocationListener = new MyLocationListener();
			if (!mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
				mProvider = LocationManager.NETWORK_PROVIDER;
			}
			mLocationManager.requestLocationUpdates(mProvider, 0,// MIN_TIME_TO_UPDATE,
					0,// MIN_DIST_TO_UPDATE,
					mLocationListener);
			l = mLocationManager.getLastKnownLocation(mProvider);

			final ArrayList<Canteen> canteens = this.fetchCanteens();

			CustomAdapter adapter = new CustomAdapter(this, R.layout.browse_list_entry, R.id.browse_place_name, canteens);
			ListView lv = (ListView) findViewById((R.id.browseListView));
			lv.setAdapter(adapter);

			lv.setOnItemClickListener(new OnItemClickListener() {
				public void onItemClick(AdapterView<?> parent, View view,
						int position, long id) {
					Intent i = new Intent(getApplicationContext(), CanteenActivity.class); 

					Canteen canteen = canteens.get(position);
					i.putExtra("name", canteen.getName());
					i.putExtra("id", canteen.getId());

					BrowseActivity.this.startActivity(i);
				}
			});
			//no need update anymore
			mLocationManager.removeUpdates(mLocationListener);
		}
	}

	public void onResume() {
		super.onResume();
		if(!drawn) {
			drawn = true;
			mInflater = (LayoutInflater) getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
			isDataLoaded = false;
			mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
			mLocationListener = new MyLocationListener();
			if (!mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
				mProvider = LocationManager.NETWORK_PROVIDER;
			}
			mLocationManager.requestLocationUpdates(mProvider, 0,// MIN_TIME_TO_UPDATE,
					0,// MIN_DIST_TO_UPDATE,
					mLocationListener);
			l = mLocationManager.getLastKnownLocation(mProvider);

			final ArrayList<Canteen> canteens = this.fetchCanteens();

			CustomAdapter adapter = new CustomAdapter(this, R.layout.browse_list_entry, R.id.browse_place_name, canteens);
			ListView lv = (ListView) findViewById((R.id.browseListView));
			lv.setAdapter(adapter);

			lv.setOnItemClickListener(new OnItemClickListener() {
				public void onItemClick(AdapterView<?> parent, View view,
						int position, long id) {
					Intent i = new Intent(getApplicationContext(), CanteenActivity.class); 

					Canteen canteen = canteens.get(position);
					i.putExtra("name", canteen.getName());
					i.putExtra("id", canteen.getId());

					BrowseActivity.this.startActivity(i);
				}
			});
			//no need update anymore
			mLocationManager.removeUpdates(mLocationListener);
		}
	}

	public InputStream fetchImage(String address) throws MalformedURLException, IOException {
		URL url = new URL(address);
		URLConnection connection = url.openConnection();
		connection.setUseCaches(true);
		Object content = connection.getContent();

		return (InputStream) content;
	}



	public ArrayList<Canteen> fetchCanteens()
	{
		ArrayList<Canteen> listItems = new ArrayList<Canteen>();

		try {
			URL url = new URL("http://soledroid.huytoan.com/canteen");
			URLConnection tc = url.openConnection();
			tc.setUseCaches(true);
			BufferedReader in = new BufferedReader(new InputStreamReader(tc.getInputStream()));

			String line;
			while ((line = in.readLine()) != null) {
				JSONArray ja = new JSONArray(line);

				for (int i = 0; i < ja.length(); i++) {
					JSONObject jo = (JSONObject) ja.get(i);
					Canteen canteen = new Canteen(jo.getInt("id"), jo.getString("name"), jo.getString("image"),
							jo.getString("description"), jo.getString("latitude"), jo.getString("longitude"), jo.getInt("no_of_stalls"));
					listItems.add(canteen);
				}
			}

			isDataLoaded = true;
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return listItems;
	}


	private class CustomAdapter extends ArrayAdapter<Canteen> {
		public CustomAdapter(Context context, int resource, int textViewResourceId, List<Canteen> objects) {
			super(context, resource, textViewResourceId, objects);
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {   
			ViewHolder holder = null;
			TextView placeNameView = null;
			TextView placeDistance = null;
			WebImageView placeImageView = null;
			Canteen rowData = getItem(position);

			if(convertView == null) {
				convertView = mInflater.inflate(R.layout.browse_list_entry, null);
				holder = new ViewHolder(convertView);
				convertView.setTag(holder);
			}

			holder = (ViewHolder) convertView.getTag();

			placeNameView = holder.getTitle();
			placeNameView.setText(rowData.getName());

			Location dest = new Location(mProvider);
			dest.setLatitude(Float.valueOf(rowData.getLatitude()));
			dest.setLongitude(Float.valueOf(rowData.getLongitude()));

			placeDistance = holder.getDistance();
			placeDistance.setText( Integer.toString((int)(l.distanceTo(dest))) + " meters away");

			placeImageView = holder.getImage();

			if(rowData.getImage() == null) {
				//placeImageView.setImageResource(R.drawable.not_available);
			} else {
				//try {
					placeImageView.setImageUrl(rowData.getImage());
					placeImageView.loadImage();
				
			}

			return convertView;
		}
	}

	private class ViewHolder {
		private View mRow;
		private TextView mNameView = null;
		private TextView mDistanceView = null;
		private WebImageView mImageView = null; 

		public ViewHolder(View row) {
			mRow = row;
		}

		public TextView getTitle() {
			if(mNameView == null) {
				mNameView = (TextView) mRow.findViewById(R.id.browse_place_name);
			}
			return mNameView;
		}  

		public TextView getDistance() {
			if(mDistanceView == null) {
				mDistanceView = (TextView) mRow.findViewById(R.id.browse_place_dist);
			}
			return mDistanceView;
		}

		public WebImageView getImage() {
			if(mImageView == null){
				mImageView = (WebImageView) mRow.findViewById(R.id.browse_place_img);
			}
			return mImageView;
		}
	}

	public class MyLocationListener implements LocationListener {
		public void onLocationChanged(Location location) {
			if (location != null) {
				l = location;
			}
		}

		public void onProviderDisabled(String provider) {
			mProvider = (provider == LocationManager.GPS_PROVIDER) ? LocationManager.NETWORK_PROVIDER
					: LocationManager.GPS_PROVIDER;
			Toast.makeText(getApplicationContext(), "Switch provider",
					Toast.LENGTH_SHORT);
		}

		public void onProviderEnabled(String provider) {
			mProvider = (provider == LocationManager.GPS_PROVIDER) ? LocationManager.GPS_PROVIDER
					: LocationManager.NETWORK_PROVIDER;
			Toast.makeText(getApplicationContext(), "Switch provider",
					Toast.LENGTH_SHORT);
		}

		public void onStatusChanged(String provider, int status, Bundle extras) {
			if (status != LocationProvider.AVAILABLE) {
				mProvider = (provider == LocationManager.GPS_PROVIDER) ? LocationManager.NETWORK_PROVIDER
						: LocationManager.GPS_PROVIDER;
			}
			Toast.makeText(getApplicationContext(), "Switch provider",
					Toast.LENGTH_SHORT);
		}
	}
	
	 @Override
		public boolean onCreateOptionsMenu(Menu menu) {
			boolean result = super.onCreateOptionsMenu(menu);
			MenuInflater inflater = getMenuInflater();
			inflater.inflate(R.menu.menu, menu);
			return result;
		}
	    
	    @Override
		public boolean onOptionsItemSelected(MenuItem item) {
			Intent i;
			switch(item.getItemId()) {
			case R.id.menu_search:
				onSearchRequested();
				return true;
			case R.id.menu_preferences:
				showPreferences();
				return true;
			}
			return super.onOptionsItemSelected(item);
		}
	    
	    private void showPreferences() {
			Intent i = new Intent(this, SettingsActivity.class);
			startActivity(i);
		}
}
